import http from "@/axios/index.js";
import { handleSuccess, handleError } from "@/api/index.js";

// 文档管理API
export const DocumentApi = {
    // 分页查询文档
    list(params) {
        return http.get('/api/doc/list', { params })
            .then(res => handleSuccess(res, '查询成功'))
            .catch(err => handleError(err, '查询失败'))
    },

    // 生成新文档
    generate(caseId) {
        return http.post('/api/doc/application', { caseId })
            .then(res => handleSuccess(res, '生成成功'))
            .catch(err => handleError(err, '生成失败'))
    },

    // 获取文档详情
    detail(id) {
        return http.get(`/api/doc/detail/${id}`)
            .then(res => handleSuccess(res, '获取详情成功'))
            .catch(err => handleError(err, '获取详情失败'))
    },

    // 获取相关法律条款
    laws(docId) {
        return http.post('/api/doc/laws', { docId, position: 0 })
            .then(res => handleSuccess(res, '获取法律条款成功'))
            .catch(err => handleError(err, '获取法律条款失败'))
    },

    // 导出文档
    export(docId, format) {
        return http.post('/api/doc/export', { docId, format }, { responseType: 'blob' })
            .then(res => {
                const url = window.URL.createObjectURL(new Blob([res.data]));
                const link = document.createElement('a');
                link.href = url;
                link.setAttribute('download', `document_${docId}.${format}`);
                document.body.appendChild(link);
                link.click();
                return handleSuccess(res, '导出成功');
            })
            .catch(err => handleError(err, '导出失败'))
    },

    // 签名文档
    sign(docId, signImage) {
        return http.post('/api/doc/sign', { docId, signImage })
            .then(res => handleSuccess(res, '签名成功'))
            .catch(err => handleError(err, '签名失败'))
    },

    // 获取模板列表
    templates() {
        return http.get('/api/doc/templates')
            .then(res => handleSuccess(res, '获取模板成功'))
            .catch(err => handleError(err, '获取模板失败'))
    },

    // 添加模板
    addTemplate(template) {
        return http.post('/api/doc/templates', template)
            .then(res => handleSuccess(res, '添加模板成功'))
            .catch(err => handleError(err, '添加模板失败'))
    }
};